package cl.jpavlich.mpm.view;

import static org.metawidget.inspector.InspectionResultConstants.HIDDEN;

import java.awt.BorderLayout;
import java.awt.Dialog.ModalityType;
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.net.MalformedURLException;

import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.border.EmptyBorder;

import org.metawidget.inspector.annotation.UiAction;
import org.metawidget.inspector.annotation.UiComesAfter;
import org.metawidget.inspector.annotation.UiHidden;
import org.metawidget.inspector.commons.jexl.UiJexlAttribute;
import org.metawidget.swing.Facet;
import org.metawidget.swing.SwingMetawidget;
import org.metawidget.swing.layout.FlowLayout;

import cl.jpavlich.mpm.model.ModPackage;
import cl.jpavlich.mpm.model.ModRepository;
import cl.jpavlich.mpm.services.Bundle;
import cl.jpavlich.mpm.services.PersistenceUtils;
import cl.jpavlich.mpm.view.metawidgets.ListTableModel;
import javax.swing.JToolBar;
import javax.swing.JButton;
import javax.swing.ImageIcon;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;
import java.awt.event.KeyEvent;
import java.awt.event.InputEvent;
import javax.swing.JSeparator;
import javax.swing.SwingConstants;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JRadioButtonMenuItem;

public class MPM_MainWindow extends JFrame {

	private static final long serialVersionUID = 8842723574602123709L;

	private JPanel contentPane;
	private JTable tableModPackages;
	private final SwingMetawidget mwModPackage;
	private ModRepository repository = PersistenceUtils.createRepository();
	private final ListTableModel<ModPackage> modelModPackages;
	private SwingMetawidget mwModPackageButtons;
	private JScrollPane scrollPane;
	private JSplitPane splitPane;
	private InstallationEditor installationEditor;
	private JToolBar toolBar;
	private JButton button;
	private JButton button_1;
	private JMenuItem mntmOpen;
	private JMenuItem mntmSave;
	private JMenuItem mntmInstallPackage;
	private JMenuItem mntmUninstallPackage;
	private JSeparator separator;
	private JMenuItem mntmExit;
	private JButton button_2;
	private JSeparator separator_1;
	private JButton button_3;
	private JSeparator separator_2;
	private JMenu mnPackages;
	private JMenu mnSettings;
	private JRadioButtonMenuItem rdbtnmntmBasicMode;
	private JRadioButtonMenuItem rdbtnmntmPackageEditMode;

	/**
	 * Create the frame.
	 */
	public MPM_MainWindow() {
		installationEditor = new InstallationEditor();
		installationEditor.setModalityType(ModalityType.APPLICATION_MODAL);
		
		
		setTitle("Minecraft Package Manager");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 689, 466);

		JMenuBar menuBar = new JMenuBar();
		setJMenuBar(menuBar);

		JMenu mnFile = new JMenu("File");
		mnFile.setMnemonic('f');
		menuBar.add(mnFile);
		// FIXME Bundle menu item texts
		mntmOpen = new JMenuItem("Open");
		mntmOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_MASK));
		mnFile.add(mntmOpen);
		
		mntmSave = new JMenuItem("Save");
		mntmSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK));
		mnFile.add(mntmSave);
		
		separator = new JSeparator();
		mnFile.add(separator);
		
		mntmExit = new JMenuItem("Exit");
		mntmExit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, InputEvent.ALT_MASK));
		mnFile.add(mntmExit);
		
		mnPackages = new JMenu("Packages");
		mnPackages.setMnemonic('p');
		menuBar.add(mnPackages);
		
		mntmInstallPackage = new JMenuItem("Install package");
		mnPackages.add(mntmInstallPackage);
		mntmInstallPackage.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I, InputEvent.CTRL_MASK));
		
		mntmUninstallPackage = new JMenuItem("Uninstall package");
		mnPackages.add(mntmUninstallPackage);
		mntmUninstallPackage.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_U, InputEvent.CTRL_MASK));
		
		mnSettings = new JMenu("Settings");
		mnSettings.setMnemonic('s');
		menuBar.add(mnSettings);
		
		ButtonGroup bg = new ButtonGroup();
		
		rdbtnmntmBasicMode = new JRadioButtonMenuItem("Basic mode");
		rdbtnmntmBasicMode.setSelected(true);
		mnSettings.add(rdbtnmntmBasicMode);
		
		rdbtnmntmPackageEditMode = new JRadioButtonMenuItem("Package edit mode");
		mnSettings.add(rdbtnmntmPackageEditMode);
		
		bg.add(rdbtnmntmBasicMode);
		bg.add(rdbtnmntmPackageEditMode);
		
		
		contentPane = new JPanel();
		splitPane = new JSplitPane();

		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);
		modelModPackages = new ListTableModel<ModPackage>(
				ModPackage.class, repository.getPackages(), Bundle.getInstance(), "Name");

		mwModPackage = GUIUtils.createMetaWidget(true);

		contentPane.add(splitPane, BorderLayout.CENTER);

		tableModPackages = new JTable(modelModPackages);
		scrollPane = new JScrollPane(tableModPackages);
		splitPane.setLeftComponent(scrollPane);
		splitPane.setRightComponent(mwModPackage);

		tableModPackages.setPreferredScrollableViewportSize(new Dimension(150,500));
		tableModPackages.setShowHorizontalLines(false);
		tableModPackages.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				mwModPackage.setToInspect(modelModPackages
						.getValueAt(tableModPackages.getSelectedRow()));
				mwModPackage.setReadOnly(true);
				mwModPackageButtons.setToInspect(MPM_MainWindow.this);
			}
		});
		tableModPackages.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		tableModPackages.setModel(modelModPackages);
		
		
		
		
		toolBar = new JToolBar();
		contentPane.add(toolBar, BorderLayout.NORTH);
		
		button = new JButton("");
		button.setToolTipText(Bundle.getInstance().getString("buttons.open.repository.file"));
		button.setIcon(new ImageIcon(MPM_MainWindow.class.getResource("/toolbarButtonGraphics/general/Open24.gif")));
		toolBar.add(button);
		
		button_1 = new JButton("");
		button_1.setIcon(new ImageIcon(MPM_MainWindow.class.getResource("/toolbarButtonGraphics/general/Save24.gif")));
		toolBar.add(button_1);
		
		separator_1 = new JSeparator();
		separator_1.setOrientation(SwingConstants.VERTICAL);
		toolBar.add(separator_1);
		
		button_2 = new JButton("");
		button_2.setIcon(new ImageIcon(MPM_MainWindow.class.getResource("/toolbarButtonGraphics/general/Import24.gif")));
		toolBar.add(button_2);
		
		button_3 = new JButton("");
		button_3.setIcon(new ImageIcon(MPM_MainWindow.class.getResource("/toolbarButtonGraphics/general/Remove24.gif")));
		toolBar.add(button_3);
		
		separator_2 = new JSeparator();
		separator_2.setOrientation(SwingConstants.VERTICAL);
		toolBar.add(separator_2);

		mwModPackageButtons = GUIUtils.createMetaWidget(false);
		mwModPackageButtons.setMetawidgetLayout(new FlowLayout());
		mwModPackageButtons.setToInspect(this);
		
		Facet facetButtons = new Facet();
		facetButtons.setName("buttons");
		facetButtons.setOpaque(false);
//		facetButtons.add(mwModPackageButtons);

		mwModPackage.add(facetButtons);
		GUIUtils.center(this);

	}

	@UiAction
	@UiJexlAttribute(name = HIDDEN, expression = "!this.readOnly")
	public void installMod() {
		ModPackage mp = mwModPackage.getToInspect();
		if (mp != null) {
			try {
				mp.install();
			} catch (Exception e) {
				e.printStackTrace();
				
				GUIUtils.showErrorDialog(e);
				return;
			}
		}
	}
	

	@UiAction
	@UiJexlAttribute(name = HIDDEN, expression = "!this.readOnly")
	public void edit() {
		mwModPackage.setReadOnly(false);
		mwModPackage.setToInspect(mwModPackage.getToInspect());
		mwModPackageButtons.setToInspect(this);
	}

	@UiAction
	@UiJexlAttribute(name = HIDDEN, expression = "this.readOnly")
	@UiComesAfter("editInstallation")
	public void doneEditing() {

		try {
			GUIUtils.save(mwModPackage);
			mwModPackage.setReadOnly(true);
			mwModPackageButtons.setToInspect(this);

		} catch (Exception e) {
			JOptionPane.showMessageDialog(this, e.getMessage(), "Save Error",
					JOptionPane.ERROR_MESSAGE);
			return;
		}
	}

	@UiAction
	@UiJexlAttribute(name = HIDDEN, expression = "this.readOnly")
	@UiComesAfter("updateLocalFilename")
	public void editInstallation() {
		
		installationEditor.edit((ModPackage) mwModPackage.getToInspect());
	}
	
	@UiHidden
	public boolean isReadOnly() {
		return mwModPackage.isReadOnly();
	}
	
	@UiAction
	@UiJexlAttribute(name = HIDDEN, expression = "this.readOnly")
	public void updateLocalFilename() {
		ModPackage mp = mwModPackage.getToInspect();
		if (mp.getDownloadURL() != null && !mp.getDownloadURL().toString().isEmpty()) {
			try {
				System.out.println("Remote file: " + mp.getDownloadURL().toURL().getFile());
				File f = new File (mp.getDownloadURL().toURL().getFile());
				
				mp.setLocalFilename(f.getName());
				mwModPackage.setToInspect(mp);
			} catch (MalformedURLException e) {
				// do nothing
			}
		}
	}


}
